<!-- 加速终端 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px 0;">
      <div class="top">
        <div class="title">已注册终端</div>
        <!-- <el-button class="btn" type="primary" @click="addTerminal()">添加终端</el-button> -->
      </div>
      <div>
        <el-table border :data="tableData"  style="width: 100%; margin: 15px 0">
          <el-table-column type="index" label="序号" align="center" width="50"></el-table-column>
          <el-table-column prop="Department" label="从属部门" align="left"></el-table-column>
          <el-table-column prop="Name" label="终端名称" align="left"></el-table-column>
          <el-table-column prop="RealnameFix" label="硬件标识" align="left"></el-table-column>
          <el-table-column prop="ComputerName" label="计算机名称" align="left"></el-table-column>
          <el-table-column prop="OsInfo" label="操作系统" align="left"></el-table-column>
          <el-table-column prop="Mobile" label="手机号" align="left"></el-table-column>
          <el-table-column prop="UserID" label="共享用户名" align="left"></el-table-column>
          <el-table-column label="操作"  width="150px">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.row)">修改</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="title">申请终端</div>
      <div>
        <el-table border :data="RegEmployeeData"  style="width: 100%; margin: 15px 0">
          <!-- <el-table-column prop="Name" label="电脑名称" align="left"></el-table-column> -->
          <!-- <el-table-column prop="HostIP" label="IP地址" align="left"></el-table-column> -->
          <el-table-column type="index" label="序号" align="center" width="50"></el-table-column>
          <!-- <el-table-column prop="Mac" label="MAC地址" align="left"></el-table-column> -->
          <el-table-column prop="Department" label="从属部门" align="left"></el-table-column>
          <el-table-column prop="Name" label="终端名称" align="left"></el-table-column>
          <el-table-column prop="HardID" label="硬件标识" align="left"></el-table-column>
          <el-table-column prop="ComputeName" label="计算机名称" align="left"></el-table-column>
          <el-table-column prop="OsInfo" label="操作系统" align="left"></el-table-column>
          <el-table-column prop="Mobile" label="手机号" align="left"></el-table-column>
          <el-table-column prop="UserID" label="共享用户名" align="left"></el-table-column>
          <el-table-column prop="TransTime" label="申请时间" align="left"></el-table-column>
          <el-table-column label="操作" align="left" width="150px">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleregister(scope.row)">注册</el-button>
              <el-button size="mini" type="danger" @click="handleregisterDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-row>
    <el-dialog
      :close-on-press-escape=false
      :title="title"
      :visible.sync="dialogVisible"
      v-el-drag-dialog
      width="40%">
      <el-form label-width="120px" :model="RegEmployeeForm" :rules="rules" ref="RegEmployeeForm">
        <el-row>
          
          <!-- <el-col :span="12">
            <el-form-item label='实名绑定信息:' prop="RealnameFix">
              <el-input v-model="RegEmployeeForm.RealnameFix" :disabled="title==='注册终端'"></el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label='终端名称:' prop="Name">
              <el-input v-model="RegEmployeeForm.Name" :disabled="title==='修改终端'"></el-input>
            </el-form-item>
          </el-col>
          <el-col  :span="24">
            <el-form-item label='从属部门:' class="cascader" prop="Department">
              <el-cascader
                ref="cascaderAddr"
                style="width:100%;"
                v-model="RegEmployeeForm.Department"
                placeholder="请选择部门"
                clearable
                :show-all-levels="false"
                :options="options"
                :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'DepartmentName', value: 'DepartmentName', ID: 'ID'}"
                @visible-change="elCascaderOnlick"
                @expand-change="elCascaderOnlick"
                @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label='电话:'>
              <el-input v-model="RegEmployeeForm.Phone"></el-input>
            </el-form-item>
          </el-col> -->
          <el-col  :span="24">
            <el-form-item label='手机:' prop="Mobile">
              <el-input v-model="RegEmployeeForm.Mobile"></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label='邮箱:' prop="EMail">
              <el-input v-model="RegEmployeeForm.EMail"></el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label='共享用户名:' prop="UserID">
              <el-input v-model="RegEmployeeForm.UserID"></el-input>
            </el-form-item>
          </el-col>
          <el-col  :span="24">
            <el-form-item label='硬件标识：' prop="HardID">
              <el-input v-model="RegEmployeeForm.HardID" disabled v-if="title!='修改终端'"></el-input>
              <el-input v-model="RegEmployeeForm.RealnameFix" disabled v-if="title==='修改终端'"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { connrequest } from "@/api/firstPage"
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { treeing, getTreeData, parseTime } from "@/utils/index.js";
export default {
  directives: { elDragDialog },
  data() {
    return {
      title: '',
      dialogVisible: false,
      RegEmployeeForm:{},
      options: [],
      tableData: [],
      RegEmployeeData: [],
      terminalName: [],
      RealnameFix: [],
      DID:'',
      rules:{
        RealnameType: [
          { required: true, message: '请选择准入方式', trigger: 'change' }
        ],
        Name: [
          { required: true, message: '请输入终端名称'}
        ],
        Department: [
          { required: true, message: '请选择从属部门', trigger: 'blur'}
        ],
        RealnameFix: [
          { required: true, message: '请输入绑定信息'}
        ],
        Mobile:[
          {
            validator: function(rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false && value) {
                callback(new Error("手机号格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        EMail:[
          {
            validator: function(rule, value, callback) {
              if (/^\w{1,64}@[a-z0-9\-]{1,256}(\.[a-z]{2,6}){1,2}$/i.test(value) == false  && value) {
                callback(new Error("邮箱格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        UserID:[
          { required:true, message:'请输入共享用户名', trigger:'blur'}
        ]
      }
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.GetDepartment()
    this.GetRegEmployee()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},
  methods: {
    async GetEmployee(){
      let terminalName = []
      let RealnameFix = []
      const res = await connrequest('GetEmployee')
      res.Data = res.Data.map(item=>{
        item.RealnameType = item.RealnameType == '1' ? 'mac' : 'ip'
        terminalName.push(item.Name)
        RealnameFix.push(item.RealnameFix)
        return item
      })
      this.tableData = res.Data
      // 保存所有终端名称和准入模式
      this.terminalName = terminalName
      this.RealnameFix = RealnameFix
    },
    async GetRegEmployee(){
      const res = await connrequest('GetRegEmployee')
      res.Data = res.Data.map(item=>{
        item.TransTime = parseTime(item.TransTime)
        return item
      })
      this.RegEmployeeData = res.Data
    },
    radiochange(val){
      if(this.title === '注册终端'){
        this.RegEmployeeForm.RealnameFix = val === '1' ? this.registerform.Mac : this.registerform.HostIP
      }
    },
    // 添加终端
    addTerminal(){
      this.title = '添加终端'
      this.$nextTick(()=>{
        this.$refs['RegEmployeeForm'].clearValidate()
      })
      this.RegEmployeeForm = {}
      this.dialogVisible = true
    },
    handleEdit(row){
      this.title = '修改终端'
      this.$nextTick(()=>{
        this.$refs['RegEmployeeForm'].clearValidate()
      })
      row.RealnameType = row.RealnameType === 'mac' ? '1' : '2'
      // row.Department = [row.Department]
      this.RegEmployeeForm = {...row}
      this.dialogVisible = true
    },
    handleregister(row){
      this.title = '注册终端'
      this.$nextTick(()=>{
        this.$refs['RegEmployeeForm'].clearValidate()
      })
      row.Name = row.Name
      row.RealnameType = '2'
      row.RealnameFix = row.HostIP
      this.registerform = row
      this.RegEmployeeForm = {...row}
      this.dialogVisible = true
    },
    handleDelete(row){
      row.RealnameType = row.RealnameType === 'mac' ? 1 : 2
      this.$confirm('此操作将永久删除该终端, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( async () => {
        const data = {
          Data:{
            ...row
          }
        }
        const res = await connrequest('DelEmployee', data)
        if(res.Status.StatusCode === 0){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.GetEmployee()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleregisterDelete(row){
      this.$confirm('此操作将永久删除该终端, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( async () => {
        const data = {
          Data:{
            HardID: row.HardID
          }
        }
        const res = await connrequest('DelRegEmployee', data)
        if(res.Status.StatusCode === 0){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.GetRegEmployee()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    async GetDepartment(){
      const res = await connrequest('GetDepartment')
      this.options = getTreeData(treeing(res.Data))
      this.GetEmployee()
    },
    handleChange(arr,node){
      let DID = this.$refs['cascaderAddr'].getCheckedNodes()[0].data.ID
      this.DID = DID
    },
    elCascaderOnlick(){
      let that = this;
      setTimeout(function() {
        document.querySelectorAll(".el-cascader-node__label").forEach((el) => {
          el.onclick = function() {
            this.previousElementSibling.click();
            that.$refs.cascaderAddr.dropDownVisible = false;
          };
        });
      }, 100);
    },
    submit(){
      this.$refs['RegEmployeeForm'].validate( async(valid) => {
        if(valid){
          if(this.title === '添加终端' || this.title === '注册终端'){
            let terminalName = this.terminalName.filter(item => { return item === this.RegEmployeeForm.Name })
            let RealnameFix = this.RealnameFix.filter(item => { return item === this.RegEmployeeForm.RealnameFix })
            if(terminalName.length > 0){
              this.$message.error('该终端名称已经存在')
              return false
            }
            if(RealnameFix.length > 0){
              this.$message.error('该准入信息已经存在')
              return false
            }
            if(Array.isArray(this.RegEmployeeForm.Department)){
              this.RegEmployeeForm.Department = this.RegEmployeeForm.Department[this.RegEmployeeForm.Department.length - 1]
            }
            this.RegEmployeeForm.RealnameType = this.RegEmployeeForm.RealnameType * 1
            let data = {
              Data:{
                ...this.RegEmployeeForm,
                DID: this.DID,
                RealnameFix:this.RegEmployeeForm.HardID
              }
            }
            // console.log(this.RegEmployeeForm);
            const res = await connrequest('AddEmployee', data)
            if(res.Status.StatusCode === 0){
              if(this.title === '注册终端'){
                const data = {
                  Data:{
                    HardID: this.registerform.HardID
                  }
                }
                await connrequest('DelRegEmployee', data)
                this.GetRegEmployee()
              }
              this.$message({
                type: 'success',
                message: '添加终端成功'
              });
              this.GetEmployee()
              
              this.dialogVisible = false
            }
          }else{
            // console.log(1111111);
            let RealnameFix = this.RealnameFix.filter(item => { return item === this.RegEmployeeForm.RealnameFix })
            // if(RealnameFix.length > 0){
            //   this.$message.error('该准入信息已经存在')
            //   return false
            // }
            if(Array.isArray(this.RegEmployeeForm.Department)){
              this.RegEmployeeForm.Department = this.RegEmployeeForm.Department[this.RegEmployeeForm.Department.length - 1]
            }
            this.RegEmployeeForm.RealnameType = this.RegEmployeeForm.RealnameType * 1
            let data = {
              Data:{
                ...this.RegEmployeeForm
              }
            }
            const res = await connrequest('ModifyEmployee', data)
            if(res.Status.StatusCode === 0){
              this.$message({
                type: 'success',
                message: '修改终端成功'
              });
              this.GetEmployee()
              this.dialogVisible = false
            }
          }
        }
      })
    }
  }
}
</script>
<style scoped lang='scss'>
/* @import url(); 引入css类 */
.top{
  display:flex;
  justify-content:space-between;
  align-items: center;
}
// /* cascader 隐藏单选样式 start */
// 	::v-deep .cascader .el-cascader-panel .el-radio {
// 		display: none !important;
// 	}
</style>
<style>
.el-cascader-panel .el-radio {
  display: none;
}
</style>
